#include <kernel.h>
#include <pa4.h>
//#include <buf.h>
//#include <disk.h>

/*
 * Part A 4/4. buf_put()
 * buf_put() processes each write request.
 * If policy is POLICY_WRITE_THROUGH,
 *     then find a buffer that already stores the block_no block, stores new data to it
 *     and finally store the data into disk.
 * Otherwise (POLICY_DELAYED_WRITE),
 *     then you have to handle requests based on the policy.
 */

//********************************************************
dsk_buffer_p searchNode(int block_no)
{
	dsk_buffer_p m= buf_head;
	while(m!=NULL)
	{
		if(m->block_no==block_no) return m;
		m=m->next;
	}
return NULL;
}

//********************************************************
int buf_put(struct devsw *pdev, int block_no, char *buffer, int policy) {

dsk_buffer_p tmp;
int rep_policy=PA4_BUFFER_REPLACEMENT;

if(0>block_no || block_no>1024)
{
return INVALID_BLOCK;
}

tmp=searchNode(block_no);
if(tmp==NULL)
{
tmp=buf_fetch(pdev,block_no,rep_policy);
tmp->data=buffer;
}

while(invalid[block_no]==1) resched();
invalid[block_no]=1;

  if(policy==POLICY_WRITE_THROUGH)
  {
   dskwrite(pdev,tmp->data,block_no,1);
  }
  else
  {
   tmp->dirty=1;
  }


invalid[block_no]=0;
return OK;



}//end of buf_put
